package com.sky.handler;

import com.sky.constant.JwtClaimsConstant;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;


/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
public class GlobalExceptionHandler implements GlobalFilter, Ordered {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private AntPathMatcher antPathMatcher;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();

        //判断是否需要登录拦截
        if (antPathMatcher.match(String.valueOf(request.getPath()), "/admin/employee/login")) {
            return chain.filter(exchange);
        }

        //解析token
        List<String> tokens = request.getHeaders().get("token");

        String token = null;

        if (tokens != null && !tokens.isEmpty()) {

            token = tokens.get(0);

        }

        Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
        Long empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());

        System.err.println("empId = " + empId);
        String finalUserId = empId.toString();
        ServerWebExchange webExchange = exchange.mutate().request(builder -> builder.header("user-info", finalUserId))
                .build();

        //放行
        return chain.filter(webExchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
